package com.chuanjiabao.wisdom.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.ApplicationState;
import com.chuanjiabao.wisdom.adapter.BaseFragmentAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.AuthCallbackBean;
import com.chuanjiabao.wisdom.bean.FamilyResCallbackBean;
import com.chuanjiabao.wisdom.bean.ReasionInfoCallbackBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.STSCallBackBean;
import com.chuanjiabao.wisdom.databinding.ActivityFindToSeeFamilyBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.fragment.FindToSeeFamilyFragment;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.DowloadDialog;
import com.chuanjiabao.wisdom.util.dialog.HintDeleteDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareDialog;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.lzy.okgo.utils.OkLogger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static android.view.View.GONE;

public class FindToSeeFamilyActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    ActivityFindToSeeFamilyBinding binding;
    List<Fragment> list = new ArrayList<>();
    ApplicationState applicationState = new ApplicationState();
    int position = 0;
    int currentFile = 0;
    boolean isSecret = false;
    BaseFragmentAdapter<Fragment> fragmentAdapter;
    OSSClient oss;
    String deleteId = "";
    ReasionInfoCallbackBean.DataBean reasionBean;
    private DowloadDialog mDialog;

    private static List<FamilyResCallbackBean.DataBeanX.DataBean> listBeans = new ArrayList<>();
    public static void setData(List<FamilyResCallbackBean.DataBeanX.DataBean> data) {
        listBeans.clear();
        listBeans.addAll(data);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_find_to_see_family);
        binding.setActivity(this);
        initView();

        setInfo(listBeans.get(position));
    }

    private void initView() {
        try {
            reasionBean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
            position = getIntent().getIntExtra("module_position", 0);
            isSecret = getIntent().getBooleanExtra("module_isSecret", false);
            LogUtil.e("是否是私密-->" + isSecret);
            if (isSecret) getAuth();
            else getSTS();

            deleteId = listBeans.get(position).getId() + "";
            currentFile = listBeans.get(position).getFile_type();
            if (listBeans.get(position).getFile_type() == 4) {
                binding.llModuleShare.setVisibility(View.GONE);
                binding.ivModuleDetail.setVisibility(View.GONE);
            }

            fragmentAdapter = new BaseFragmentAdapter<>(getSupportFragmentManager());
        } catch (Exception e) {
            LogUtil.e("intent 传递出错");
        }
        binding.ivModuleFinish.setOnClickListener(this);
        binding.llModuleDelete.setOnClickListener(this);
        binding.llModuleShare.setOnClickListener(this);
        binding.ivModuleDetail.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivModuleFinish:
                finish();
                break;
            case R.id.ivModuleDetail:
                Intent intent = new Intent(this, DetailActivity.class);
                intent.putExtra("module_id", deleteId);
                intent.putExtra("module_isSecret", isSecret);
                startActivity(intent);
                break;
            case R.id.llModuleShare:
                new RxPermissions(this).request(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                ).subscribe(new RxObserver<Boolean>() {

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            ToastUtil.showToast(R.string.picture_jurisdiction);
                            return;
                        }

                        ShareDialog dialog = new ShareDialog(
                                FindToSeeFamilyActivity.this,
                                listBeans.get(position).getFile_type() == 1 ? "image" : "video");
                        dialog.show();
                        dialog.setOnShareStypeClickListener(style -> {
                            try {
                                String url = oss.presignConstrainedObjectURL(
                                        listBeans.get(position).getFile_bucket(),
                                        listBeans.get(position).getFile(),
                                        30 * 60
                                );

                                switch (style) {
                                    case "Wx":
                                        new ShareAction(FindToSeeFamilyActivity.this)
                                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                                .withText("河南传家宝")
                                                .withMedia(new UMImage(FindToSeeFamilyActivity.this, url))
                                                .share();
                                        break;
                                    case "QQ":
                                        new ShareAction(FindToSeeFamilyActivity.this)
                                                .setPlatform(SHARE_MEDIA.QQ)
                                                .withText("河南传家宝")
                                                .withMedia(new UMImage(FindToSeeFamilyActivity.this, url))
                                                .share();
                                        break;
                                    case "save":
                                        downloadFile(url, listBeans.get(position).getFile_type() == 1 ? "image" : "video");
                                        break;
                                }
                            } catch (ClientException e) {
                                e.printStackTrace();
                            }
                        });
                    }

                });
                break;
            case R.id.llModuleDelete:
                new HintDeleteDialog(this)
                        .setTitle("删除文件")
                        .setContent("是否删除1项文件")
                        .setYes("确认删除")
                        .dismissNotAnim()
                        .setOnBHClickListener(new OnBHClickListener() {
                            @Override
                            public void onConfirmClick() {
                                if (isSecret) {
                                    if (currentFile == 4) deleteTextFile(deleteId);
                                    else deleteSecretFile(deleteId);
                                } else {
                                    if (currentFile == 4) deleteTextFile(deleteId);
                                    else deleteHomeFile(deleteId);
                                }
                            }
                        })
                        .show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    public void deleteHomeFile(String fileStr) {
        if (!TextUtils.isEmpty(fileStr)) {
            HTTPAPI.getInstance().deleteHomeFile(fileStr, new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    if (!StringUtil.isFail(s)) {
                        StringUtil.showFail(FindToSeeFamilyActivity.this, s);
                    } else {
                        RefreshMessageEvent event = new RefreshMessageEvent();
                        event.setType("detail");
                        event.setId(currentFile + "");
                        EventBus.getDefault().post(event);

                        ToastUtil.showToast("删除成功");
                        finish();
                    }
                }
            });
        }
    }

    public void deleteSecretFile(String fileStrs) {
        HTTPAPI.getInstance().deleteSecretFile(fileStrs, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FindToSeeFamilyActivity.this, s);
                } else {
                    ToastUtil.showToast("删除成功");
                    finish();
                }
            }
        });
    }

    private void deleteTextFile(String fileStrs) {
        HTTPAPI.getInstance().deleteHomeText(fileStrs, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FindToSeeFamilyActivity.this, s);
                } else {
                    if (!isSecret) {
                        RefreshMessageEvent event = new RefreshMessageEvent();
                        event.setType("detail");
                        event.setId(currentFile + "");
                        EventBus.getDefault().post(event);
                    }

                    ToastUtil.showToast("删除成功");
                    finish();
                }
            }
        });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (applicationState.isMainSliding() && position == 1) {
            applicationState.setMainSliding(false);
        }
        LogUtil.e("滑动位置-->" + position);
        deleteId = listBeans.get(position).getId() + "";
        currentFile = listBeans.get(position).getFile_type();
        if (currentFile == 4) {
            binding.llModuleShare.setVisibility(View.GONE);
            binding.ivModuleDetail.setVisibility(View.GONE);
        } else {
            binding.llModuleShare.setVisibility(View.VISIBLE);
            binding.ivModuleDetail.setVisibility(View.VISIBLE);
        }

        setInfo(listBeans.get(position));
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (!applicationState.isMainSliding() && state != ViewPager.SCROLL_STATE_IDLE) {
            applicationState.setMainSliding(true);
        }
    }

    public void setInfo(FamilyResCallbackBean.DataBeanX.DataBean bean) {
        if (isSecret) {
            binding.tvModuleName.setText(reasionBean.getTruename());
            if (TextUtils.isEmpty(reasionBean.getAvatar())) {
                LogUtil.e("图片为空");
                binding.tvModuleNameHead.setVisibility(View.VISIBLE);
                binding.ivModuleHead.setVisibility(GONE);
                if (!TextUtils.isEmpty(reasionBean.getTruename())) {
                    binding.tvModuleNameHead.setText(reasionBean.getTruename().substring(0, 1));
                } else {
                    binding.tvModuleNameHead.setText("空");
                }
            } else {
                binding.ivModuleHead.setVisibility(View.VISIBLE);
                binding.tvModuleNameHead.setVisibility(GONE);

                GlideUtil.setCircleMethod(
                        FindToSeeFamilyActivity.this,
                        reasionBean.getAvatar(),
                        binding.ivModuleHead
                );
            }
        } else {
            binding.tvModuleName.setText(bean.getTruename());
            if (TextUtils.isEmpty(bean.getAvatar())) {
                LogUtil.e("图片为空");
                binding.tvModuleNameHead.setVisibility(View.VISIBLE);
                binding.ivModuleHead.setVisibility(GONE);
                binding.tvModuleNameHead.setText(bean.getTruename().substring(0, 1));
            } else {
                binding.ivModuleHead.setVisibility(View.VISIBLE);
                binding.tvModuleNameHead.setVisibility(GONE);

                GlideUtil.setCircleMethod(
                        FindToSeeFamilyActivity.this,
                        bean.getAvatar(),
                        binding.ivModuleHead
                );
            }
        }
    }

    public void getSTS() {
        HTTPAPI.getInstance().getSTS(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取STS成功" + s);
                if (!StringUtil.isFail(s)) {
                    SpUtils.clear(FindToSeeFamilyActivity.this);
                    startActivity(new Intent(FindToSeeFamilyActivity.this, LoginActivity.class));
                    ToastUtil.showToast("登陆过期，请重新登陆");
                } else {
                    final STSCallBackBean bean = GsonUtil.GsonToBean(s, STSCallBackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {
                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(FindToSeeFamilyActivity.this, "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(200);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }
        });
    }

    public void getAuth() {
        HTTPAPI.getInstance().getAuth(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取私密授权成功" + s);
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FindToSeeFamilyActivity.this, s);
                } else {
                    final AuthCallbackBean bean = GsonUtil.GsonToBean(s, AuthCallbackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {
                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(FindToSeeFamilyActivity.this, "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(200);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                for (FamilyResCallbackBean.DataBeanX.DataBean dataBean : listBeans) {
                    list.add(new FindToSeeFamilyFragment(oss, dataBean));
                }
                fragmentAdapter.addData(list);
                binding.vpModule.setAdapter(fragmentAdapter);
                binding.vpModule.setCurrentItem(position);
                binding.vpModule.addOnPageChangeListener(FindToSeeFamilyActivity.this);
            } catch (Exception e) {
                LogUtil.e("fragment添加出错");
            }
        }
    };

    private void downloadFile(String url, String type) {
        File appDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                        .getAbsoluteFile();
        if (!appDir.exists())
            //noinspection ResultOfMethodCallIgnored
            appDir.mkdir();

        String fileName = TextUtils.equals("image", type)
                ? "picture_" + System.currentTimeMillis() + ".jpg"
                : "video_" + System.currentTimeMillis() + ".mp4";

        HTTPAPI.getInstance().download(url, new FileCallback(
                appDir.getAbsolutePath(),
                fileName
        ) {
            @Override
            public void onBefore(BaseRequest request) {
                mDialog = new DowloadDialog(FindToSeeFamilyActivity.this);
                mDialog.show();
            }

            @Override
            public void onSuccess(File file, Call call, Response response) {
                //发送广播通知系统图库刷新数据
                Uri uri = Uri.fromFile(file);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                ToastUtil.showToast("已保存到相册！");
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
                ToastUtil.showToast("文件下载失败！");
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                OkLogger.i("currentSize:" + currentSize);
                OkLogger.i("totalSize:" + totalSize);
                if (mDialog != null) mDialog.setProgress((int) (progress * 100));
            }

        });
    }

}
